package com.ruoyi.web.controller.security;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.security.domain.SecurityTradingCalendar;
import com.ruoyi.security.service.ISecurityTradingCalendarService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 证券交易日历Controller
 * 
 * @author yeoman
 * @date 2025-01-15
 */
@Controller
@RequestMapping("/security/trading-calendar")
@Validated
public class SecurityTradingCalendarController extends BaseController {
    
    private String prefix = "security";
    
    @Resource
    private ISecurityTradingCalendarService securityTradingCalendarService;
    
    /**
     * 证券交易日历页面
     */
    @GetMapping()
    public String tradingCalendar() {
        return prefix + "/trading-calendar";
    }
    
    /**
     * 查询证券交易日历列表
     */
    @GetMapping("/list")
    @ResponseBody
    public AjaxResult list(@RequestParam Integer year) {
        Map<Integer, List<SecurityTradingCalendar>> monthGroups = securityTradingCalendarService.selectTradingCalendarByYearGroupByMonth(year);
        return AjaxResult.success("查询成功", monthGroups);
    }
    
    
    /**
     * 同步全年交易日历数据
     */
    @Log(title = "同步交易日历", businessType = BusinessType.INSERT)
    @PostMapping("/sync")
    @ResponseBody
    public AjaxResult sync(@RequestParam @NotNull(message = "年份不能为空") Integer year) {
        try {
            logger.info("开始同步{}年交易日历数据", year);
            String result = securityTradingCalendarService.sync(year);
            logger.info("同步{}年交易日历数据完成：{}", year, result);
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("同步{}年交易日历数据失败", year, e);
            return AjaxResult.error("同步失败：" + e.getMessage());
        }
    }
    
    /**
     * 同步指定年月交易日历数据
     */
    @Log(title = "同步交易日历", businessType = BusinessType.INSERT)
    @PostMapping("/sync/{year}/{month}")
    @ResponseBody
    public AjaxResult sync(@PathVariable @NotNull(message = "年份不能为空") Integer year, 
                          @PathVariable @NotNull(message = "月份不能为空") Integer month) {
        try {
            logger.info("开始同步{}年{}月交易日历数据", year, month);
            String result = securityTradingCalendarService.sync(year, month);
            logger.info("同步{}年{}月交易日历数据完成：{}", year, month, result);
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("同步{}年{}月交易日历数据失败", year, month, e);
            return AjaxResult.error("同步失败：" + e.getMessage());
        }
    }
}
